<template>
  <div style="background: #2c3e50">
     <h1 style="color:Orange">图片标注网站</h1>
      <el-menu
    :default-active="activeIndex2"
    class="el-menu-demo"
    mode="horizontal"
    @select="handleSelect"
    background-color="#545c64"
    text-color="#fff"
    active-text-color="#ffd04b">
        <el-menu-item index="1">上传资源</el-menu-item>
        <el-menu-item index="2">任务广场</el-menu-item>
        <el-menu-item index="3">个人资源</el-menu-item>
        <el-menu-item index="4">继续标注</el-menu-item>
        <el-menu-item index="5">退出登录</el-menu-item>
        <el-menu-item index="6">我的任务</el-menu-item>
        <el-menu-item index="7">已登录账号：{{user.username}}</el-menu-item>
      </el-menu>
    <!-- 上传图片/视频部分，条件展示 -->
    <div v-show="showTasks" style="background: aliceblue;margin-top: 0">
      <h3 style="color: red;">请在此上传一张或一组图片</h3>
      <el-upload
        style="width: 50%;margin-left: 25%"
    class="upload-demo"
    action="http://127.0.0.1:8000/uploadimages/"
    accept=".png,.jpg"
    :auto-upload="false"
    :on-change="handleChanged"
    :data="myData"
    :before-remove="beforeRemove"
    :before-upload="beforeUpload"
    :on-success="uploadSuccess"
    ref="upload"
    multiple
    :limit="10"
    :on-exceed="handleExceed"
    :file-list="fileList"
    list-type="picture">
    <el-button size="small" type="primary">选择图片</el-button>
    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，每次最多上传10个文件</div>
      </el-upload>
     <el-button size="small" type="warning" @click="UploadToDjango" style="margin-top: 2%">上传图片</el-button>
      <el-divider style="size:2px"></el-divider>
      <h3 style="color:red;">上传视频，系统按帧截取图片后自动存入个人资源库保存</h3>
      <p class="type_title">
        </p>
        <div class="pic_img">
            <div class="pic_img_box">
                <el-upload class="avatar-uploader"
                           action="http://127.0.0.1:8000/uploadvideos/"
                           accept=".mp4"
                           :data="myVideoData"
                           :auto-upload="false"
                           multiple
                           :on-change="handleVideoSelect"
                           ref="videoupload"
                           :file-list="videoList"
                           :limit="1"
                           :on-progress="uploadVideoProcess"
                           :on-success="handleVideoSuccess"
                           :before-upload="beforeUploadVideo"
                ><el-button size="small" type="primary">选择视频</el-button>
                </el-upload>
                </div>
          <p class="Upload_pictures">
            <span></span>
            <span style="margin-bottom: 10px">最多可以上传1个视频，建议大小50M，推荐格式mp4</span>
          </p>
          <el-button type="primary" @click="uploadVideos" style="float: right;margin-top: 3%">上传视频</el-button>
            </div>
        </div>




    <!-- 任务展示部分，条件展示 -->
    <div v-show="showSquare">
      <el-table
        ref="multipleTable"
        :data="missionlist"
        tooltip-effect="dark"
        style="width: 100%;text-align: center"
        @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="100">
        </el-table-column>
        <el-table-column label="任务编号" width="80">
          <template slot-scope="scope">
            <p>{{scope.row.ids}}</p>
          </template>
        </el-table-column>
        <el-table-column label="图片示例" >
        　　<template slot-scope="scope">
        　　　　<img :src="scope.row.paths" width="250" height="150" alt="任务示例图"/>
        　　</template>
        </el-table-column>
        <el-table-column label="标注图片数量" width="120">
          <template slot-scope="scope">
            <p>{{scope.row.number}}</p>
          </template>
        </el-table-column>
        <el-table-column label="任务发布者" width="120">
          <template slot-scope="scope">
            <p>{{scope.row.owners}}</p>
          </template>
        </el-table-column>
        <el-table-column label="发布日期" width="100">
          <template slot-scope="scope">
            <p>{{scope.row.date}}</p>
          </template>
        </el-table-column>
        <el-table-column label="描述" width="120">
          <template slot-scope="scope">
            <p>{{scope.row.des}}</p>
          </template>
        </el-table-column>
    </el-table>
      <el-button type="primary" @click="AcceptMission" style="float: right;margin-top: 3%">领取任务(限一项)</el-button>
    </div>
</div>
</template>

<script>
import axios from "axios";

export default {
  name: "MainPage",
  data(){
      return{

        videoFlag: false,
        //上传进度条
        videoUploadPercent: "",
        selections: [],
        videoList: [],
        fileList: [],
        files: [],
        videofiles: [],
        myVideoData: {token: '',},
        missionlist: [],
        showSquare: false,
        showTasks: false,
        myData: {token: ''},
        user: {
          username: '未登录',
        },
        activeIndex2:'1'
      }
  },mounted() {
    axios.post('/api/username', {
                token: window.sessionStorage.getItem("token")
              }).then((response)=>{
                if (response.data.code === 200){
                  this.user.username = response.data.username
                  this.myData.token = window.sessionStorage.getItem("token")
                  this.myVideoData.token = window.sessionStorage.getItem("token")
                  window.sessionStorage.setItem("user", response.data.username)
                }
                else {
                  this.$router.push({path:"/LoginPage"})
                }
            })
  },
  methods:{
    handleSelect(key, keyPath){
      //根据activeindex2的不同选择来处理
      if (key === '2')
      {
        this.showTasks = false
        this.getMissionList()
        this.showSquare = true
      }
      else if (key === '6')
      {
        this.$router.push({path:"/MyMissions"})
      }
      else if (key === '5')
      {
        this.LogOut()
      }
      // 查看个人资源
      else if (key === '3')
      {
        this.showTasks = false
        this.showSquare = false
        this.$router.push({path:"/MyGallery"})
      }
      // 上传图片
      else if (key === '1')
      {
        // 显示发布任务界面并准备上传图片
        this.showTasks = true
        this.showSquare = false
      }
      else if (key === '4')
      {
        this.showSquare = false
        this.showTasks = false
        this.$router.push({path:"/ImageMarking"})
      }
    },
    // 退出登录
    LogOut(){
      window.sessionStorage.removeItem("token")
      this.$router.push({path:"/LoginPage"})
    },
    // 将图片上传到后端
    UploadToDjango(){
      let formData = new FormData()
      formData.append("file",this.files)
      formData.append("token", this.myData.token)
      this.$refs.upload.submit(formData)
    },
    //处理上传文件时超出文件限制个数的情况
    handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 10 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
    // 处理删除文件的情况
    beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
    beforeUpload(file){
      //在上传前检查格式和大小
      if (!(file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg')) {
          this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
        }
      if (file.size/1024/1024 > 10){
          this.$message.error('上传头像图片大小不能超过 10MB!');
        }
    },
    // 上传成功，删除已上传列表
    uploadSuccess (data) {
        this.$refs.upload.clearFiles()
        this.$message.success("上传成功!")
    },
    // 需要上传的文件改变时
    handleChanged(file){
      this.files = file.raw
    },
    // 获取任务列表
    getMissionList(){
        this.missionlist = []
      axios.get("/showmissionlist/").then(
        (response)=>{
          let owners = response.data.owners
          let dates = response.data.dates
          let descriptions = response.data.des
          let images = response.data.m
          let ids = response.data.ids
          let num = response.data.number
          for (const e in owners)
          {
            this.missionlist.push({"owners": owners[e], "paths": images[e], "des": descriptions[e], "date": dates[e], "number": num[e], "ids": ids[e]})
          }
          console.log(this.missionlist)
        }
      )
    },
    // 用户在任务列表中的选择发生变化处理函数
    handleSelectionChange(val) {
      if (val.length > 1){
        this.$refs.multipleTable.clearSelection()
        val = []
        this.$alert("一个用户同时只能执行一项任务，别太贪了")
      }
      this.selections = val
      console.log(val)
    },
    // 领取任务
    AcceptMission(){
      if (this.selections.length === 0)
      {
        this.$alert("你还没有选择任务")
        return
      }
      let choice = this.selections[0]["ids"]
      axios.post(
        "/AcceptMission/",
        {
          "token": window.sessionStorage.getItem("token"),
          "missionid": choice
        }
      ).then(
        (response)=>{
          // 如果失败
          if (response.data.code === 403)
          {
            // 提示错误
            this.$alert(response.data.message)
          }
          else{
            this.$alert("领取成功！将刷新页面显示")
            this.getMissionList()
          }
        }
      )
    },

    beforeUploadVideo(file){
      let fileSize = file.size / 1024 / 1024 < 50;
      if (['video/mp4'].indexOf(file.type) === -1) {
        this.$alert("只允许上传mp4格式视频!")
        return false;
      }
      if (!fileSize) {
        this.$alert("视频大小不能超过50MB");
        return false;
      }
      this.isShowUploadVideo = false;
    },
    //进度条
    uploadVideoProcess(event, file, fileList) {
      this.videoFlag = true;
      this.videoUploadPercent = file.percentage.toFixed(0) * 1;
    },
    handleVideoSuccess(data){
      this.$refs.videoupload.clearFiles()
      this.$message.success("上传成功, 请到个人资源仓库查看并处理截取结果")
    },
    // 上传视频到django后端
    uploadVideos(){
      let form = new FormData()
      form.append("token", this.myVideoData.token)
      form.append("file",this.videofiles)
      this.$refs.videoupload.submit(form)
    },
    handleVideoSelect(file){
      this.videofiles = file.raw
    }
  }
}
</script>

<style scoped>

</style>
